#!/usr/bin/env python
# -*- coding: utf-8 -*-

#####################################################################
#
# RFID READER SDK FOR PYTHON
# AUTHOR: zengkai001@qq.com
# DATE: 2025-01-24
#
#####################################################################

# {
#     "ReaderConnStr":"RDType=M60;CommType=COM;COMName=COM1;BaudRate=38400;Frame=8E1;BusAddr=255;"
# }

# ReaderConnStr1 = "RDType=RL8000;CommType=USB;AddrMode=0;SerNum="

ReaderConnStr2 = "RDType=UM200;CommType=COM;COMName=ttyUSB0;BaudRate=38400;Frame=8E1;BusAddr=255;"

import os
import time
from rfid_reader import RFIDReader

def tag_callback(tags):
    """标签回调函数"""
    print(f"\n发现新标签: {tags}")

def test_uhf_operations():
    """测试UHF读写器功能"""
    print("\n=== 测试UHF读写器 ===")
    rfid = RFIDReader(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'x86_64/libGZAE_rfid.so'))
    rfid.open_device(ReaderConnStr2)
    
    info = rfid.get_device_info()
    print(f"设备信息: {info}")
        
    # if you want to test inventory/read/write, pls set True
    if False:  
        # 执行单次盘点
        print("\n开始盘点...")
        rfid.start_inventory()
        
        # 获取并打印标签信息
        tag_result = rfid.get_tag_info()
        tags = tag_result['tags'] if tag_result and 'tags' in tag_result else []
        print(f"\n检测到标签数量: {len(tags) if tags else 0}")
        
        if tags:
            print("\n=== 标签详细信息 ===")
            for i, tag in enumerate(tags, 1):
                print(f"标签 {i}:")
                print(f"  EPC(UID): {tag.get('EPC', tag.get('UID', 'N/A'))}")
                print(f"  天线(AntID): {tag['AntId']}")
                print(f"  类型(TagType): {tag['TagType']}")
                print(f"  检测次数: {tag['Count']}")
                if 'DSFID' in tag:
                    print(f"  DSFID: {tag['DSFID']}")
                if 'Data' in tag:
                    print(f"  数据(Data): {tag['Data']}")
        

        # 内存类型：
        # mem_type 参数：
        # 0: RESERVED
        # 1: EPC
        # 2: TID
        # 3: USER

        # 示例 EPC 和访问密码
        epc = "45bd3000c225d500200005f77ecf0005"  # 替换为实际 EPC
        access_pwd = "00000000"  # 默认访问密码

        # 读取 TID 信息
        print("Reading TID memory...")
        tid_data = rfid.read_tag(epc, block_start=0, block_count=6, access_pwd=access_pwd, mem_type=2)
        if tid_data:
            print(f"TID Data: {tid_data.hex()}")
        else:
            print("Failed to read TID memory.")

        # # 写入 USER 区数据  ###kzeng VERIFIED!!! 
        # print("Writing to USER memory...")
        # user_data = b'\x12\x34\x56\x78'  # 示例数据
        # success = rfid.write_tag(epc, block_start=0, data=user_data, access_pwd=access_pwd, mem_type=3)
        # if success:
        #     print("Successfully wrote to USER memory.")
        # else:
        #     print("Failed to write to USER memory.")


if __name__ == "__main__":
    # test_hf_operations()
    test_uhf_operations()
